package com.tansun.easycare.rule.decisiontree.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.core.utils.IdGen;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblock;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.DataSetTreeVo;
import com.tansun.easycare.rule.common.model.BaseBean;
import com.tansun.easycare.rule.common.model.DomainItem;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.DThen;
import com.tansun.easycare.rule.common.rulebasebean.DWhen;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.common.service.RuleDrlParseService;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.common.symbol.SymbolGuide;
import com.tansun.easycare.rule.datamodel.entity.RuleDataDomain;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.decisiontree.dao.RuleTreeNodeDao;
import com.tansun.easycare.rule.decisiontree.entity.DecisionTreeEntity;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeConditions;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeNode;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeParam;
import com.tansun.easycare.rule.decisiontree.entity.RuleTreeScene;
import com.tansun.easycare.rule.decisiontree.model.DecisionSubNode;
import com.tansun.easycare.rule.decisiontree.model.DecisionSubNodeItem;
import com.tansun.easycare.rule.decisiontree.model.RuleTreeManageVO;
import com.tansun.easycare.rule.decisiontree.service.DecisionTreeService;
import com.tansun.easycare.rule.decisiontree.service.RuleTreeConditionsService;
import com.tansun.easycare.rule.decisiontree.service.RuleTreeParamService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.policytree.service.RuleTreeSceneService;
import com.tansun.easycare.rule.refemodel.entity.RuleReleModel;
import com.tansun.easycare.rule.refemodel.service.RuleReleModelService;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulegroup.model.DomainInfo;
import com.tansun.easycare.rule.rulegroup.model.RuleExpessVO;
import com.tansun.easycare.rule.rulegroup.model.RuleSetExpressVO;
import com.tansun.easycare.rule.rulegroup.service.RuleParseExpService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.MClass;
import com.tansun.rule.utils.StringUtils;

@Service("decisionTreeService")
public class DecisionTreeServiceImpl extends RuleBaseServiceImpl<RuleTreeNodeDao, RuleTreeNode>  implements DecisionTreeService {

	@Autowired
	private  RuleManageService  ruleManageService;
	
	@Autowired
    private  RuleVersioninfoService  ruleVersioninfoService;
	
	@Autowired
	private  RuleTreeParamService  ruleTreeParamService;
	
	@Autowired
	private  RuleTreeConditionsService  ruleTreeConditionsService;
	
	@Autowired
	private  RuleReferenceDataService  ruleReferenceDataService;
	
	@Autowired
	private  RuleTreeSceneService  ruleTreeSceneService;
	
	@Autowired
	private  DataBomService  dataBomService;
	
	@Autowired
	private  RuleReleModelService  ruleReleModelService;
	@Autowired
	private  RuleDataparamsService  ruleDataparamsService;
    @Autowired
    private RuleCodeblockService ruleCodeblockService;
    @Autowired
    private RuleParseExpService  ruleParseExpService;
    
    @Autowired
    private RuleDrlParseService ruleDrlParseService;
    

    
	@Override
	public void saveOrUpdateDecisionTree(RuleManage tree) throws BizException {
		   boolean  rootFlag  = false;
		   if (!"true".equals(tree.getIsTemp())) {
			 tree.setStatus("1");
		   } else {
			 tree.setStatus("3");
		   }
		   if (org.apache.commons.lang3.StringUtils.isEmpty(tree.getId())){
			   rootFlag  =true;
			   
		   }
		   RuleManage  ruleManage  = tree;
		   ruleManage.setModelType(RuleModelTypeEnum.DecisionTree.getCode());
		   this.ruleManageService.saveOrUpdate(ruleManage);
		   if (rootFlag){
			   //创建根节点
			   RuleTreeNode ruleTreeNode  = new  RuleTreeNode();
			   ruleTreeNode.setNodeId("ROOT_V");
			   ruleTreeNode.setManageId(ruleManage.getId());
			   ruleTreeNode.setPid("0");
			   ruleTreeNode.setNodeName(ruleManage.getName());
			   ruleTreeNode.setType("open");
			   ruleTreeNode.setNum(0);
			   ruleTreeNode.setFloor(0);
			   ruleTreeNode.setIsLeaf("false");
			   ruleTreeNode.setIsReleModel("0");
			   ruleTreeNode.setVersion(ruleManage.getVersion());
			   ruleTreeNode.setProjectCode(ruleManage.getProjectCode());
			   this.save(ruleTreeNode);
               
		   }
	}

	@Override
	public RuleTreeManageVO getTreeInfo(String treeId, String version,String projectCode, String temp) throws BizException {
		RuleTreeManageVO  resultMap = new RuleTreeManageVO();
		RuleManage  ruleManageVO = this.ruleManageService.getById(treeId);
        if(ruleManageVO==null){
        	ruleManageVO = ruleManageService.findByCode(treeId, projectCode);
        }
//		Map<String,Object>  paramMap  = new  HashMap();
//		paramMap.put("id", treeId);
//		List<RuleManageVO> list =this.ruleManageService.findRuleManageVO(paramMap);
//		if (list == null || list.size()<1){
//		   throw new   BizException("E-000600");
//		}
//		RuleManageVO  ruleManageVO  =  list.get(0);
        
		resultMap.setRuleManage(ruleManageVO);
		
		if(version == null) version  = ruleManageVO.getVersion();
		if("1".equals(temp)) {
			version = ruleManageVO.getActiveVersion();
		}
		//
		RuleTreeParam  ruleTreeParam  = new  RuleTreeParam();
		ruleTreeParam.setManageId(ruleManageVO.getId());
		ruleTreeParam.setVersion(version);
		List<RuleTreeParam> paramList =this.ruleTreeParamService.findList(ruleTreeParam);
		List<DecisionSubNodeItem> resultItems = new ArrayList();
		DecisionSubNodeItem  subNodeItem = null;
		for (RuleTreeParam treeParam :paramList){
			 subNodeItem  = new  DecisionSubNodeItem();
			 subNodeItem.setClassName(treeParam.getClassName());
			 subNodeItem.setNameCN(treeParam.getNamecn());
			 subNodeItem.setNameEN(treeParam.getNameen());
			 subNodeItem.setDataType(treeParam.getDataType());
			 subNodeItem.setDefaultValue(treeParam.getDefaultValue());
			 subNodeItem.setDomain(treeParam.getDomain());
			 subNodeItem.setIsDerives(treeParam.getIsDerives());
			 subNodeItem.setPosition(treeParam.getPosition());
             subNodeItem.setCollection(treeParam.getCollection());
			 resultItems.add(subNodeItem);
		}
		resultMap.setResultItems(resultItems);
		//
		RuleTreeNode   treeNodeInfo  = new  RuleTreeNode();
		treeNodeInfo.setManageId(ruleManageVO.getId());
		treeNodeInfo.setVersion(version);
		List<RuleTreeNode>  nodeList = this.findList(treeNodeInfo);
		List<DecisionSubNode>  subNodeList = new ArrayList();
		DecisionSubNode  subNode = null;

		DecisionSubNodeItem  deSubNodeItem  = null;
		RuleTreeConditions  treeConditionsInfo  = null; 
		
		treeConditionsInfo = new  RuleTreeConditions();
		treeConditionsInfo.setVersion(version);
		treeConditionsInfo.setManageId(ruleManageVO.getId());
		Page<RuleTreeConditions> page = new Page<RuleTreeConditions>();
		page.setOrderBy("seq");
		treeConditionsInfo.setPage(page);
		List<RuleTreeConditions> condList = this.ruleTreeConditionsService.findList(treeConditionsInfo);//获取全部条件节点的规则详情
		
		Map<String,List<RuleTreeConditions>> map = new HashMap<>(); //key为nodeId；value是list

		for(RuleTreeConditions item:condList) {
			if(map.containsKey(item.getNodeId())) {//若map中已存在该key值，则找出对应的value值，并将当前的的value值add进集合中
				List<RuleTreeConditions> list=new ArrayList<RuleTreeConditions>();//对应map中的value
				list = map.get(item.getNodeId());
				list.add(item);			
			}else {	
				List<RuleTreeConditions> list=new ArrayList<RuleTreeConditions>();//对应map中的value
				list.add(item);
				map.put(item.getNodeId(), list);//通过遍历condList获取map
			}
		}

		for (RuleTreeNode treeNode :nodeList){
			List<DecisionSubNodeItem> nodeItems = new ArrayList();
			List<DecisionSubNodeItem> reItems = new ArrayList();
			subNode = new  DecisionSubNode();
			subNode.setId(treeNode.getNodeId());
			subNode.setPid(treeNode.getPid());
			subNode.setType(treeNode.getType());
			subNode.setName(treeNode.getNodeName());
			subNode.setNum(treeNode.getNum());
			subNode.setFloor(treeNode.getFloor());
			subNode.setIsLeaf(treeNode.getIsLeaf());
			subNode.setIsReleModel(treeNode.getIsReleModel());
			subNode.setNodeItems(nodeItems);
			subNode.setResultItems(reItems);
			subNode.setNodehtml(treeNode.getNodehtml());
			subNode.setCfyResult(treeNode.getCfyResult());
			if (treeNode.getIsReleModel()!=null && treeNode.getIsReleModel().equals("1")) {
				List<RuleReleModel> releModelList = this.ruleReleModelService.findReleModelList(treeNode.getNodeId(),version);
				subNode.setReleModelItems(releModelList);
			}
			subNodeList.add(subNode);
		
			List<RuleTreeConditions> nodeCondList = map.get(treeNode.getNodeId());//根据nodeId获取对应的节点规则详情
			if(nodeCondList==null)
				continue;
			for (RuleTreeConditions treeConditions :nodeCondList){
				deSubNodeItem  = new  DecisionSubNodeItem();
				try {
					BeanUtils.copyProperties(deSubNodeItem, treeConditions);
					deSubNodeItem.setNameCN(treeConditions.getNamecn());
					deSubNodeItem.setNameEN(treeConditions.getNameen());
					deSubNodeItem.setLeftOpt(treeConditions.getLeftOpt());
					deSubNodeItem.setRightOpt(treeConditions.getRightOpt());
					
				} catch (Exception e) {
					throw  new  BizException(e,"E-000000");
				} 
				if (subNode.getIsLeaf() != null && subNode.getIsLeaf().equals("true")){
					reItems.add(deSubNodeItem);
				}else {
					nodeItems.add(deSubNodeItem);
				}
				
			}
			
			
		}
		resultMap.setNodeList(subNodeList);
		RuleVersioninfo  ruleVersion =  this.ruleManageService.findRuleVersionInfo(projectCode,ruleManageVO.getId() );
		if (ruleVersion != null) {
			resultMap.setDatasetNames(ruleVersion.getDatasetNames());
		}
		return resultMap;
	}

	@Override
	public void saveOrUpdate(DecisionTreeEntity treeEntity) throws BizException {

		RuleManage ruleManage = this.ruleManageService.get(treeEntity.getRuleManage().getId());
		if (ruleManage == null)
			throw new BizException("E-000600");
		ruleManage.setStatus("1");
		ruleManage.setIsSingle(treeEntity.getRuleManage().getIsSingle());
		ruleManage.setIsTemp(treeEntity.getRuleManage().getIsTemp());
		boolean flag = true;
		String isTemp = treeEntity.getRuleManage().getIsTemp();
		if (isTemp != null && "true".equals(isTemp)) {
			flag = false;
		}
        ruleManage.setName(treeEntity.getRuleManage().getName());
        if (ruleManageService.isExists(ruleManage)) {
            throw new BizException("E-000111");
        }
        treeEntity.setRuleManage(ruleManage);
        ruleManage = ruleManageService.saveOrUpdate(treeEntity.getRuleManage());
		
		List<DecisionSubNode> subNodeList = treeEntity.getNodeList();
		RuleTreeNode ruleTreeNode = null;
		List<RuleTreeNode> ruleTreeList = new ArrayList();
		RuleTreeParam ruleTreeParam = null;
		List<RuleTreeParam> treeParamList = new ArrayList();

		RuleTreeConditions ruleTreeConditions = null;
		List<RuleTreeConditions> treeCondList = new ArrayList();
		Map<String, RuleTreeNode> map = new HashMap<String, RuleTreeNode>();
		String rootId = null;
		int m =0;
		for (DecisionSubNode subNode : subNodeList) {
			ruleTreeNode = new RuleTreeNode();
			ruleTreeNode.setNodeId(subNode.getId());
			if (subNode.getIsLeaf() == null)
				ruleTreeNode.setIsLeaf("false");
			ruleTreeNode.setIsLeaf(subNode.getIsLeaf());
			ruleTreeNode.setManageId(ruleManage.getId());
			ruleTreeNode.setNodeName(subNode.getName());
			ruleTreeNode.setNum(subNode.getNum());
			ruleTreeNode.setPid(subNode.getPid());
			ruleTreeNode.setProjectCode(ruleManage.getProjectCode());
			ruleTreeNode.setType(subNode.getType());
			ruleTreeNode.setVersion(ruleManage.getVersion());
			ruleTreeNode.setIsNewRecord(false);
            ruleTreeNode.setIsReleModel(subNode.getIsReleModel());
			ruleTreeNode.setFloor(subNode.getFloor());
			ruleTreeNode.setIsReleModel(subNode.getIsReleModel());
			ruleTreeNode.setNodehtml(subNode.getNodehtml());
			ruleTreeNode.setCfyResult(subNode.getCfyResult());
			ruleTreeList.add(ruleTreeNode);
			if (subNode.getPid() != null && "0".equals(subNode.getPid())) {
				rootId = subNode.getId();
			}
			if (ruleTreeNode.getNum()== null){
				ruleTreeNode.setNum(m);
			}
			if (ruleTreeNode.getType()== null){
				ruleTreeNode.setType("open");
			}
			m++;
			if (subNode.getIsReleModel() !=null && subNode.getIsReleModel().equals("1")) {
				if (subNode.getReleModelItems() != null && subNode.getReleModelItems().size()>0) {
					//ruleReleModelService.deleteByNodeId(ruleTreeNode.getNodeId());
					String[]  paramName = new String[] {"nodeId","manageId","projectCode","version"};
					Object[]  paramValue = new Object[] {ruleTreeNode.getNodeId(),ruleTreeNode.getManageId(),ruleTreeNode.getProjectCode(),ruleManage.getVersion()};
					ruleReleModelService.insertBatch(subNode.getReleModelItems(),paramName,paramValue,true);
				}
			}
		}
		
		for (RuleTreeNode tmpNode : ruleTreeList) {
			map.put(tmpNode.getNodeId(), tmpNode);
		}
		
		//获取解析工具对象
		//RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
		//收集函数变量
		Map<String,RuleDataparams> funcparamMap = new HashMap<String, RuleDataparams>();
		Map<String, RuleTreeParam> paramMap = new HashMap<String, RuleTreeParam>();
		// 收集引用数据
		Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
		String key = null;
		for (DecisionSubNode subNode : subNodeList) {
			if (subNode.getPid() != null && subNode.getPid().equals("0"))
				continue;
			ruleTreeNode = map.get(subNode.getId());
			if (subNode.getIsLeaf() != null && Boolean.valueOf(subNode.getIsLeaf())) {
				int   k=0;
				for (DecisionSubNodeItem reNodeItem : subNode.getResultItems()) {
					ruleTreeConditions = new RuleTreeConditions();
					try {
						makeRuleCondition(reNodeItem, ruleTreeConditions,ruleTreeNode, ruleManage);
						treeCondList.add(ruleTreeConditions);
						if (ruleTreeConditions.getSeq()== null){
							ruleTreeConditions.setSeq(k);
						}
						k++;
						ruleTreeParam = new RuleTreeParam();
						BeanUtils.copyProperties(ruleTreeParam, reNodeItem);
						ruleTreeParam.setFloor(ruleTreeNode.getFloor());
						ruleTreeParam.setManageId(ruleManage.getId());
						ruleTreeParam.setNamecn(reNodeItem.getNameCN());
						ruleTreeParam.setNameen(reNodeItem.getNameEN());
						ruleTreeParam.setProjectCode(ruleManage.getProjectCode());
						ruleTreeParam.setVersion(ruleManage.getVersion());
						paramMap.put(ruleTreeParam.getClassName() + "-"+ ruleTreeParam.getNameen(), ruleTreeParam);
						key = ruleTreeParam.getClassName() + "|"+ ruleTreeParam.getNameen() + "|out";
						ruleReferenceDataService.collectCommonData(ruleTreeParam, key, "out", ruleManage, refMap);
						
						List<RuleTreeParam> paramList = getdsInfo(ruleManage.getProjectCode(),reNodeItem.getFormula());
						if(paramList!=null){
							for (RuleTreeParam param : paramList) {
								param.setProjectCode(ruleManage.getProjectCode());
								param.setManageId(ruleManage.getId());
								param.setVersion(ruleManage.getVersion());
								//paramMap.put(param.getClassName() + "-"+ param.getNameen(), param);
								key = param.getClassName() + "|"+ param.getNameen() + "|in";
								ruleReferenceDataService.collectCommonData(param, key, "in", ruleManage, refMap);
							}
						}
						if (reNodeItem.getControlValue()!=null && reNodeItem.getControlValue().startsWith("{") && reNodeItem.getControlValue().endsWith("}")) {
							Map<String, String> controlMap = (new ObjectMapper()).readValue(reNodeItem.getControlValue(), Map.class);
							String CONTROLKEY = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
							ruleReferenceDataService.collectFromMap(controlMap, CONTROLKEY, "in", ruleManage, refMap);
						}
					} catch (Exception e) {
						throw new BizException(e, "E-000000");
					}
				}
				if (subNode.getIsReleModel() !=null && subNode.getIsReleModel().equals("1")&& subNode.getReleModelItems() !=null) {
					List<RuleReleModel> releList = subNode.getReleModelItems();
					for (RuleReleModel relModel:releList) {
						if (relModel.getIsfuncparam() !=null &&relModel.getIsfuncparam().equals("1")) {
							RuleCodeblock   codeInfo  =new  RuleCodeblock();
							codeInfo.setProjectCode(ruleManage.getProjectCode());
							codeInfo.setParameterId(relModel.getRefeCode());
							List<RuleCodeblock> codeList =this.ruleCodeblockService.findList(codeInfo);
							if (codeList != null  && codeList.size()>0) {
								try {
									this.ruleDrlParseService.collectReferenceData(ruleManage, codeList.get(0).getCodeBody(), refMap);
								} catch (Exception e) {
									throw  new  BizException(e, "");
								}
							}
						}	
					}
				}
			} else if(subNode.getNodeItems()!=null && subNode.getNodeItems().size() > 0) {
				int  k =0;
				List<RuleTreeConditions>  nodeCondList  = new  ArrayList<>();
				for (DecisionSubNodeItem subNodeItem : subNode.getNodeItems()) {
					ruleTreeConditions = new RuleTreeConditions();
					makeRuleCondition(subNodeItem, ruleTreeConditions,ruleTreeNode, ruleManage);
					treeCondList.add(ruleTreeConditions);
					nodeCondList.add(ruleTreeConditions);
					if (ruleTreeConditions.getSeq()== null){
						ruleTreeConditions.setSeq(k);
					}
					key = ruleTreeConditions.getClassName() + "|"+ ruleTreeConditions.getNameen() + "|in";
					if(!"1".equals(ruleTreeConditions.getIsfuncparam())) {
						
						ruleReferenceDataService.collectCommonData(ruleTreeConditions, key, "in", ruleManage, refMap);
					}else {
						//收集函数变量
						RuleDataparams ruleDataparams = new RuleDataparams();
						ruleDataparams.setClassName(ruleTreeConditions.getClassName());
						ruleDataparams.setName(ruleTreeConditions.getNameen());
						funcparamMap.put(key,ruleDataparams);
					}
					if (subNodeItem.getControlValue().startsWith("{") && subNodeItem.getControlValue().endsWith("}")) {
						try {
							Map<String, String> controlMap = (new ObjectMapper()).readValue(subNodeItem.getControlValue(), Map.class);
							String CONTROLKEY = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
							if(!"1".equals(controlMap.get("isfuncparam"))) {
								ruleReferenceDataService.collectFromMap(controlMap, CONTROLKEY, "in", ruleManage, refMap);		
							}else {
								//收集函数变量
								RuleDataparams ruleDataparams = new RuleDataparams();
								ruleDataparams.setClassName(ruleTreeConditions.getClassName());
								ruleDataparams.setName(ruleTreeConditions.getNameen());
								funcparamMap.put(CONTROLKEY,ruleDataparams);
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					List<RuleTreeParam> paramList = getdsInfo(ruleManage.getProjectCode(),ruleTreeConditions.getFormula());
					if(paramList!=null){
						for (RuleTreeParam param : paramList) {
							param.setProjectCode(ruleManage.getProjectCode());
							param.setManageId(ruleManage.getId());
							param.setVersion(ruleManage.getVersion());
							//paramMap.put(param.getClassName() + "-"+ param.getNameen(), param);
							key = param.getClassName() + "|"+ param.getNameen() + "|in";
							ruleReferenceDataService.collectCommonData(param, key, "in", ruleManage, refMap);
						}
					}
					k++;
				}
				String nodeHtml =this.parseTreeCond(nodeCondList, ruleManage.getProjectCode());
				ruleTreeNode.setNodehtml(nodeHtml);
				subNode.setNodehtml(nodeHtml);
			}else if(StringUtils.isNotEmpty(subNode.getNodehtml())) {
				this.ruleParseExpService.transformFactReference(subNode.getNodehtml(), ruleManage, refMap, funcparamMap);
			}
		}
		if(paramMap.size()==0 && treeEntity.getResultItems()!=null) {
			for (DecisionSubNodeItem ruleTreeConditions2 : treeEntity.getResultItems()) {
				RuleTreeParam ruleParam = new RuleTreeParam();
				try {
					BeanUtils.copyProperties(ruleParam, ruleTreeConditions2);
				} catch (Exception e) {
					e.printStackTrace();
				}
				ruleParam.setFloor(ruleTreeNode.getFloor());
				ruleParam.setManageId(ruleManage.getId());
				ruleParam.setNamecn(ruleTreeConditions2.getNameCN());
				ruleParam.setNameen(ruleTreeConditions2.getNameEN());
				ruleParam.setProjectCode(ruleManage.getProjectCode());
				ruleParam.setVersion(ruleManage.getVersion());
				paramMap.put(ruleParam.getClassName() + "-"+ ruleParam.getNameen(), ruleParam);
			}
		}
		this.insertBatch(ruleTreeList);
		key = "builtinParam" + "|"+ ruleManage.getCode() + "|out";
		RuleTreeParam ruleParam = new RuleTreeParam();
		ruleParam.setClassName("builtinParam");
		ruleParam.setNamecn(ruleManage.getName()+"_分类结果");
		ruleParam.setNameen(ruleManage.getCode());
		ruleParam.setDataType("String");
		ruleReferenceDataService.collectCommonData(ruleParam, key, "out", ruleManage, refMap);
        List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
        this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
		// 保存数据数据
		this.ruleReferenceDataService.saveReferenceData(refMap);
		treeParamList.addAll(paramMap.values());
		this.ruleTreeParamService.insertBatch(treeParamList);
		this.ruleTreeConditionsService.insertBatch(treeCondList);
		if (!flag)
			return;
		// 创建版本信息
		try {
			/**函数模式**/
			String context = this.writeDrl(ruleManage, rootId, subNodeList,false,ruleManage.getIsSingle());
			//String context = this.writeDrl(ruleManage, rootId, subNodeList,ruleParseDrl,true,ruleManage.getIsSingle());
			RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
	        ruleVersioninfo.init(ruleManage, context);
            ruleVersioninfo.setDatasetNames(treeEntity.getDatasetNames());
			this.ruleVersioninfoService.save(ruleVersioninfo);
		} catch (Exception e) {
			throw new BizException(e, "E-000100");
		}
	}
	
	public  String  parseTreeCond(List<RuleTreeConditions> condList,String  projectCode) {
		  RuleSetExpressVO  ruleSetExpressVO  = null; 
		  
		  RuleExpessVO ruleExpressVO  = null;
		  List<RuleExpessVO>  conditions;
		  List<RuleSetExpressVO> resList  = new  ArrayList<>();
		  Map<String, List<RuleDataDomain>> map = this.dataBomService.findDomainMap();
		  Map<String, MClass> metaMap = this.dataBomService.findMapClass(projectCode);
          int  len  = condList.size();
		  for (int i=0;i<condList.size();i++ ) {
			  RuleTreeConditions  treeCond = condList.get(i);
			  ruleSetExpressVO  = new  RuleSetExpressVO();
			  resList.add(ruleSetExpressVO);
			  //ruleSetExpressVO.setLeftOpt(treeCond.getLeftOpt());
			  ruleSetExpressVO.setSeq(i+1);
			  conditions = new ArrayList<>();
			  ruleSetExpressVO.setRightOpt(treeCond.getRightOpt());
			  //ruleSetExpressVO.setLogicOpt(treeCond.getLeftOpt());
			  ruleSetExpressVO.setConditions(conditions);
			  MClass  mclzz=metaMap.get(treeCond.getClassName());
			  String  dataType = treeCond.getDataType();
			  String  leftOpt  = null;
			  int  j = i+1;
			  if (j< len && condList.get(j) != null) {
				  leftOpt = condList.get(j).getLeftOpt();
			  }
			  if (!StringUtils.isEmpty(leftOpt)) {
				  if ("or".equals(leftOpt)) {

					  ruleSetExpressVO.setLogicOpt("||");
		  	    }else if ("and".equals(leftOpt)) {

		  	    	ruleSetExpressVO.setLogicOpt("&&"); 
			    }else {
			    	ruleSetExpressVO.setLogicOpt(leftOpt);
			    }
			  }

			  if (mclzz != null) {
				  ruleExpressVO = new  RuleExpessVO();
				  ruleExpressVO.setLabel(mclzz.getChzn());
				  ruleExpressVO.setName(mclzz.getName());
				  ruleExpressVO.setType("bom");
				  conditions.add(ruleExpressVO);
			  }
			  String  nameEn = treeCond.getNameen();
			  if (!StringUtils.isEmpty(nameEn)) {
				  ruleExpressVO = new  RuleExpessVO();
				  ruleExpressVO.setName(nameEn);
				  ruleExpressVO.setLabel(treeCond.getNamecn());
				  ruleExpressVO.setDataType(treeCond.getDataType());
				  ruleExpressVO.setType("field");
				  ruleExpressVO.setDomain(treeCond.getDomain());
				  ruleExpressVO.setId(IdGen.uuid());
				  conditions.add(ruleExpressVO);
			  }
			  String  symbol = treeCond.getSymbol();
			  if (symbol != null ) {
				  if (symbol.trim().equals(">=")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("大等于");
					  ruleExpressVO.setDrlSymbol(">= ");
					  ruleExpressVO.setJavaSymbol(">=");
					  ruleExpressVO.setType("sym");
					  ruleExpressVO.setName("gtel");
					  conditions.add(ruleExpressVO);
				  }else 
				  if (symbol.trim().equals("<=")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("小等于");
					  ruleExpressVO.setDrlSymbol("<=");
					  ruleExpressVO.setJavaSymbol("<=");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("ltel");
					  conditions.add(ruleExpressVO);
				  }else
				  if (symbol.trim().equals("==")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("等于");
					  ruleExpressVO.setDrlSymbol("==");
					  ruleExpressVO.setJavaSymbol("==");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("nequal");
					  conditions.add(ruleExpressVO);
				  }else
				  
				  if (symbol.trim().equals(">")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("大于");
					  ruleExpressVO.setDrlSymbol(">");
					  ruleExpressVO.setJavaSymbol(">");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("greate");
					  conditions.add(ruleExpressVO);
				  }else
				  
				  if (symbol.trim().equals("<")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("小于");
					  ruleExpressVO.setDrlSymbol("<");
					  ruleExpressVO.setJavaSymbol("<");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("little");
					  conditions.add(ruleExpressVO);
				  }else
				  
				  if (symbol.trim().equals("!=")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("不等于");
					  ruleExpressVO.setDrlSymbol("!=");
					  ruleExpressVO.setJavaSymbol("!=");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("nequal");
					  conditions.add(ruleExpressVO);
				  }else 	  
				  
				  if (symbol.trim().equals("contains")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("包含");
					  ruleExpressVO.setDrlSymbol("!=");
					  ruleExpressVO.setJavaSymbol("!=");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("contains");
					  conditions.add(ruleExpressVO);
				  }else 
				  
				  if (symbol.trim().equals("startsWith")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("以xxx开头");
					  ruleExpressVO.setDrlSymbol(".startsWith");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("startsWith");
					  conditions.add(ruleExpressVO);
				  }else 				  
				  if (symbol.trim().equals("以xxx结尾 ")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("以xxx开头");
					  ruleExpressVO.setDrlSymbol(".endsWith");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("endsWith");
					  conditions.add(ruleExpressVO);
				  }else if (symbol.equals("")) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel("等于");
					  ruleExpressVO.setDrlSymbol("==");
					  ruleExpressVO.setJavaSymbol("==");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName("nequal");
					  conditions.add(ruleExpressVO); 
				  }else if ("1".equals(symbol.trim())) {
		
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel(" In ");
					  ruleExpressVO.setDrlSymbol("in");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setSymtype(SymbolGuide.SYMTYP_CollExist);
					  ruleExpressVO.setName(" In ");
					  conditions.add(ruleExpressVO);
					  
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel(" ( ");
					  ruleExpressVO.setType(BaseBean.TYPE_LOGIC);
					  ruleExpressVO.setName(" ( ");
					  conditions.add(ruleExpressVO);
					  
				  }else if ("0".equals(symbol.trim())) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel(" NotIn");
					  ruleExpressVO.setDrlSymbol(" not in ");
					  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
					  ruleExpressVO.setName(" NotIn ");
					  ruleExpressVO.setSymtype(SymbolGuide.SYMTYP_CollExist);
					  conditions.add(ruleExpressVO);
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setLabel(" ( ");
					  ruleExpressVO.setType(BaseBean.TYPE_LOGIC);
					  ruleExpressVO.setName(" ( ");
					  conditions.add(ruleExpressVO);
				  }
				  
				  
			  }else {
				  ruleExpressVO = new  RuleExpessVO();
				  ruleExpressVO.setLabel("等于");
				  ruleExpressVO.setDrlSymbol("==");
				  ruleExpressVO.setJavaSymbol("==");
				  ruleExpressVO.setType(BaseBean.TYPE_SYMBOL);
				  ruleExpressVO.setName("nequal");
				  conditions.add(ruleExpressVO);
			  }
			  
			  String   controlValue =  treeCond.getControlValue();
			  if (controlValue != null && controlValue.startsWith("[")&&controlValue.endsWith("]")) {
				  controlValue  = controlValue.substring(1, controlValue.length()-1);
				  controlValue= StringUtils.replace(controlValue, "\"", "");
				  String[] vals = StringUtils.split(controlValue, ",");
				  for (String  val :vals) {
					  ruleExpressVO = new  RuleExpessVO();
					  ruleExpressVO.setType(BaseBean.OBJ_TYPE_VALUE);
					  ruleExpressVO.setDataType(treeCond.getDataType());
					  ruleExpressVO.setName(BaseBean.OBJ_TYPE_VALUE);
					  ruleExpressVO.setValue(val);
				      if (dataType != null && dataType.equals("String")&& !StringUtils.isEmpty(treeCond.getDomain())) {
						  DomainInfo domainInfo = new  DomainInfo();
						  domainInfo.setDataType(treeCond.getDataType());
						  domainInfo.setLabel(treeCond.getNamecn());
						  domainInfo.setName(treeCond.getNameen());
						  domainInfo.setType(BaseBean.TYPE_DOMAIN);
						  List<RuleDataDomain> domains =  map.get(treeCond.getDomain());
						  DomainItem  item = null;
						  List<DomainItem> domainItems = new ArrayList<>();
						  
						  for (RuleDataDomain domain: domains) {
							  item   = new  DomainItem();
							  item.setType(BaseBean.TYPE_DOMAIN);
							  item.setName(domain.getName());
							  item.setLabel(domain.getName());
							  item.setValue(domain.getDomainValue());
							  item.setId(domain.getId());
							  domainItems.add(item);
						  }
						  domainInfo.setDomainItems(domainItems);
						  ruleExpressVO.setDomainInfo(domainInfo);
						  
					  }
					  conditions.add(ruleExpressVO);   
				  }
			
			  }else {
				  ruleExpressVO = new  RuleExpessVO();
				  ruleExpressVO.setType(BaseBean.OBJ_TYPE_VALUE);
				  ruleExpressVO.setDataType(treeCond.getDataType());
				  ruleExpressVO.setName(BaseBean.OBJ_TYPE_VALUE);
				  ruleExpressVO.setValue(controlValue);
				  conditions.add(ruleExpressVO);
			  }		  
			  
			  if ("0".equals(symbol.trim()) || "1".equals(symbol.trim())) {
				  ruleExpressVO = new  RuleExpessVO();
				  ruleExpressVO.setLabel(" ) ");
				  ruleExpressVO.setType(BaseBean.TYPE_LOGIC);
				  ruleExpressVO.setName(" ) ");
				  conditions.add(ruleExpressVO);
			  }
			  
	
			 
			  
		  }
		  String  resHtml = JSON.toJSONString(resList,new PropertyFilter() {
				public boolean apply(Object object, String name, Object value) {
					if (object  instanceof RuleExpessVO ) {
						if (name.equals("forNumber") || "replace".equals(name)) {
							return  false;
						}
					}
					if (value == null) {
						value ="";
					}
					return true;
				}			  
		  });
		  return  resHtml;
		
	}
	
	@Override
	public  void  updateSetParam(String manageId,RuleSetParamInfo newSetParamInfo,RuleSetParamInfo oldParamInfo,boolean  setFlag) throws Exception {
		 RuleManage  ruleManage =  this.ruleManageService.get(manageId);
		 RuleTreeNode   treeNodeInfo  = new  RuleTreeNode();
		 treeNodeInfo.setManageId(manageId);
		 treeNodeInfo.setVersion(ruleManage.getActiveVersion());
		 List<RuleTreeNode>  nodeList = this.findList(treeNodeInfo);
		 String  rootId = null ;
		 for (RuleTreeNode treeNode :nodeList){
			 if (treeNode.getPid() != null && "0".equals(treeNode.getPid())) {
					rootId = treeNode.getNodeId();
			 }
             if ( StringUtils.isNotEmpty(treeNode.getNodehtml())){
            	 List<RuleSetExpressVO> list = this.ruleParseExpService.parseFactExpress(treeNode.getNodehtml(), newSetParamInfo,oldParamInfo, setFlag);
            	 treeNode.setNodehtml(JSON.toJSONString(list));
            	 this.save(treeNode);
             }
		}
		 
		 RuleTreeParam  ruleTreeParam  = new  RuleTreeParam();
		 ruleTreeParam.setManageId(manageId);
		 ruleTreeParam.setVersion(ruleManage.getActiveVersion());
		 List<RuleTreeParam> paramList =this.ruleTreeParamService.findList(ruleTreeParam);

		 for (RuleTreeParam treeParam: paramList) {
			 if (setFlag) {
				 if (treeParam.getClassName().equals(oldParamInfo.getCode())) {
					 treeParam.setClassName(newSetParamInfo.getCode());
	
					 this.ruleTreeParamService.save(treeParam);
				 }
				 
			 }else {
				 if (treeParam.getNameen().equals(oldParamInfo.getCode())) {
					 treeParam.setNameen(newSetParamInfo.getCode());
					 treeParam.setNamecn(newSetParamInfo.getName()); 
		
					 this.ruleTreeParamService.save(treeParam);
				 }

			 }
			
		 }
		 
		 RuleTreeConditions	treeConditionsInfo = new  RuleTreeConditions();
		 treeConditionsInfo.setVersion(ruleManage.getActiveVersion());
		 treeConditionsInfo.setManageId(ruleManage.getId());
		 Page<RuleTreeConditions> page = new Page<RuleTreeConditions>();
		 page.setOrderBy("seq");
		 treeConditionsInfo.setPage(page);
		List<RuleTreeConditions> condList = this.ruleTreeConditionsService.findList(treeConditionsInfo);
		for (RuleTreeConditions  ruleCond :condList) {
			 if (setFlag) {
				 if (ruleCond.getClassName().equals(oldParamInfo.getCode())) {
					 ruleCond.setClassName(newSetParamInfo.getCode());
	
					 this.ruleTreeConditionsService.save(ruleCond);
				 }
				 
			 }else {
				 if (ruleCond.getNameen().equals(oldParamInfo.getCode())) {
					 ruleCond.setNameen(newSetParamInfo.getCode());
					 ruleCond.setNamecn(newSetParamInfo.getName()); 
		
					 this.ruleTreeConditionsService.save(ruleCond);
				 }

			 }
		}
	
		 RuleTreeManageVO treeManageVO =  this.getTreeInfo(manageId, ruleManage.getActiveVersion(),ruleManage.getProjectCode(), "1");
		 
		String   content = this.writeDrl(ruleManage, rootId, treeManageVO.getNodeList(), false, ruleManage.getIsSingle());
		RuleVersioninfo  versInfo  = new RuleVersioninfo();
		versInfo.setManageId(ruleManage.getId());
		versInfo.setVersion(ruleManage.getActiveVersion());
	    List<RuleVersioninfo> vList =	this.ruleVersioninfoService.findList(versInfo);
	    if (vList != null && vList.size()>0) {
	    	RuleVersioninfo  ruleVer = vList.get(0);
	    	ruleVer.setRuleContent(content);
	    	this.ruleVersioninfoService.save(ruleVer);
	    }
		
	}
	
	

	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String showJavaCode(DecisionTreeEntity treeEntity) throws BizException {
		return null;
//		RuleManage ruleManage = this.ruleManageService.get(treeEntity.getRuleManage().getId());
//		if (ruleManage == null)
//			throw new BizException("E-000600");
//		ruleManage.setStatus("1");
//		ruleManage.setIsSingle(treeEntity.getRuleManage().getIsSingle());
//		ruleManage.setIsTemp(treeEntity.getRuleManage().getIsTemp());
//
//        ruleManage.setName(treeEntity.getRuleManage().getName());
//        treeEntity.setRuleManage(ruleManage);
//
//        Map<String,String> refeCodeMap = new HashMap<String,String>();
//		RuleDataparamsInfo rd = new RuleDataparamsInfo();
//		rd.setProjectcode(ruleManage.getProjectCode());
//		rd.setIsfuncparam("1");
//		List<RuleDataparamsInfo> paList  = this.ruleDataparamsService.findListWithStatus(rd);
//		for(RuleDataparamsInfo info:paList) {
//			refeCodeMap.put(info.getId(), info.getDatasetName() + "." + info.getName());
//		}
//		
//        Map<String, Bom> indexBom = dataBomService.findBomMapByProjectCode(ruleManage.getProjectCode(),null);
//        Map<String, Bom> handlerBom = BomCreator.findMapInOut(indexBom);
//        Map<String, Domain> drlDomain = this.dataBomService.findDomainByProjectCode(ruleManage.getProjectCode());
//        List<JFun> jfunList = ruleCodeblockService.genJFun(ruleManage.getProjectCode());
//        Map<String,String> funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
//        
//        Map indexBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(indexBom);
//        Map handlerBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(handlerBom);
//        Map drlDomainSC = ClassChangeUtils.changeDomainClass(drlDomain);
//        List jfunListSC = ClassChangeUtils.<JFun, com.tansun.rule.sparkCode.entity.common.jfun.JFun>changeClass(jfunList);
//        List<DecisionSubNodeSC> tempList = new ArrayList<DecisionSubNodeSC>();
//        for(DecisionSubNode decisionSubNode:treeEntity.getNodeList()) {
//        	DecisionSubNodeSC decisionSubNodeSC = ClassChangeUtils.changeDecisionSubNodeClass(decisionSubNode);
//        	tempList.add(decisionSubNodeSC);
//        }
//        RuleManageSC ruleManageSC = ClassChangeUtils.<RuleManage,RuleManageSC>changeClass(ruleManage);
//        return DecisionTreeCreate.createCode(ruleManageSC, tempList, funcParamMap, refeCodeMap, indexBomSC, handlerBomSC, drlDomainSC, jfunListSC);
	}
	
	
	private   void  makeRuleCondition(DecisionSubNodeItem subNodeItem,RuleTreeConditions ruleTreeConditions,RuleTreeNode ruleTreeNode,RuleManage ruleManage ) throws BizException{
        try {
			BeanUtils.copyProperties(ruleTreeConditions, subNodeItem);
			ruleTreeConditions.setProjectCode(ruleManage.getProjectCode());
			ruleTreeConditions.setNodeId(ruleTreeNode.getNodeId());
			ruleTreeConditions.setNamecn(subNodeItem.getNameCN());
			ruleTreeConditions.setNameen(subNodeItem.getNameEN());
			ruleTreeConditions.setVersion(ruleManage.getVersion());
			ruleTreeConditions.setManageId(ruleManage.getId());
			ruleTreeConditions.setCollection(subNodeItem.getCollection());
		} catch (Exception e) {
			throw  new  BizException(e, "E-000000");
		} 
	

	}
	

	
	private void getSilanceNodes(String pid,List<DecisionSubNode> nodeList,List<DecisionSubNode> newList,Map<String, DecisionSubNode> tempMap){
		List<DecisionSubNode> childList = getChildNodes(pid,nodeList);
		if(childList.size()>0){
			Collections.sort(childList);
			for(DecisionSubNode node : childList){
				if("true".equals(node.getIsLeaf())){
					newList.add(node);
				}else{
					tempMap.put(node.getId(), node);
					getSilanceNodes(node.getId(),nodeList,newList,tempMap);
				}
			}
		}
	}
	private List<DecisionSubNode> getChildNodes(String pid,List<DecisionSubNode> nodeList){
		List<DecisionSubNode> childList = new ArrayList<DecisionSubNode>();
		for(DecisionSubNode node : nodeList){
			if(node.getPid().equals(pid))
				childList.add(node);
		}
		return childList;
	}
	// 保存Drool文件
	private String  writeDrl( RuleManage  ruleManage,String rootId, List<DecisionSubNode> tempList,boolean isfuntionMode,String isSingle) throws Exception {
		// 获取节点信息
		funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
		List<DecisionSubNode> nodeList = new ArrayList<DecisionSubNode>();
		Map<String, DecisionSubNode> tempMap = new HashMap<String, DecisionSubNode>();

		getSilanceNodes(rootId,tempList,nodeList,tempMap);
		if (nodeList.size() == 0) return null;
		RuleCollection ruleCollection = new RuleCollection();
		ruleCollection.setDrlName(ruleManage.getCode());
		ruleCollection.setObjName(ruleManage.getName());
		ruleCollection.setContentType(RuleCollection.RULETREE);
		ruleCollection.setVersion(ruleManage.getVersion());
		// 生成动作组 从1开始递减
		int priority = 1;
        
		for (DecisionSubNode node : nodeList) {
			String ruleName = "tree_";
			List<String> ruleNameExtList = new ArrayList<String>();
			String whenStr = generateDrl(tempMap.get(node.getPid()), ruleNameExtList, tempMap,isfuntionMode);
			String thenStr = "";
			String ruleResultInfo = "";
			if((node.getResultItems()==null || node.getResultItems().size()==0) && (node.getReleModelItems()==null || node.getReleModelItems().size()==0)) {
				thenStr += "ruleHelper.setValue($insertMap,\"builtinParam."+ruleManage.getCode()+"\",\"Do Nothing\");\n";
				ruleResultInfo = "Do Nothing";
			}else {
				for (DecisionSubNodeItem child : node.getResultItems()) {
					String disabled = StringUtils.trim(child.getDisabled());
					if (disabled!=null && "true".equals(disabled)) {
						continue;
					}
					String methodStr = "ruleHelper.setValue";
					if ("List".equals(child.getCollection())) {
						methodStr = "ruleHelper.insertValue";
					}
					if(child.getControlValue()!=null) {
						String controlValue = child.getControlValue().trim();
						String temp="\""+controlValue.replaceAll("\"", "\\\\\"")+"\"";
						if (controlValue.startsWith("{") && controlValue.endsWith("}") && controlValue.contains("className")&& controlValue.contains("nameEN")) {
							Map<String, String> controlMap = (new ObjectMapper()).readValue(controlValue, Map.class);
							temp = genernalWhenStr(controlMap.get("className"),controlMap.get("nameEN"),controlMap.get("isfuncparam"));
//							if("1".equals(controlMap.get("isfuncparam"))) {
//								temp = dataMap.get(controlMap.get("className")+controlMap.get("nameEN"));
//							}else {
//								temp = "ruleHelper.getValue($insertMap,\""+controlMap.get("className")+"."+controlMap.get("nameEN")+"\")";
//							}
						}else if(!StringUtils.isEmpty(child.getFormula())){
							temp = "MathHelper.invokeMath($insertMap,metaMap,\""+child.getFormula()+"\")";
						}
						thenStr += methodStr + "($insertMap,\"" + child.getClassName() + "." + child.getNameEN() + "\"," + temp + ");\n";
					}
					
					//thenStr += methodStr + "($insertMap,\"" + child.getClassName() + "." + child.getNameEN() + "\"," + temp + ");\n";
				}
				String  releCall ="";
				if (node.getIsReleModel() !=null && node.getIsReleModel().equals("1")&&node.getReleModelItems() !=null) {
						releCall =" ruleHelper.callRuleRele";
						String  reStr ="";
						for (RuleReleModel releModel:node.getReleModelItems()) {
							if (releModel.getIsfuncparam() !=null&&releModel.getIsfuncparam().equals("1")) {
								Map<String,String> varMap  = new HashMap<>();
								varMap.put("projectCode", releModel.getProjectCode());
								varMap.put("refeCode", releModel.getRefeCode());
								varMap.put("dbName", Global.getConfig("jdbc.type"));
								List<String> paList  = this.ruleDataparamsService.findClassParam(varMap);
								if (paList !=null && paList.size()>0) {
								    reStr += super.funcParamMap.get(paList.get(0))+";\n";
								}		
							}else {
							   reStr +=releCall+"(\""+releModel.getRefeCode()+"\");\n";
							}
						}
						thenStr +=reStr;
				}	
				if(!StringUtils.isEmpty(node.getCfyResult())) {
					thenStr += "ruleHelper.setValue($insertMap,\"builtinParam."+ruleManage.getCode()+"\",\""+node.getCfyResult()+"\");\n";
					ruleResultInfo = node.getCfyResult();
				}				
			}
			String nodeIds = StringUtils.join(ruleNameExtList,"|");//规则命中节点路径
			ruleName = ruleName+nodeIds;
			RuleItem ruleItem = getCustomRule(ruleName, priority, whenStr, thenStr);
			if(isfuntionMode) {
				ruleItem.getdThen().addLogsArr("droolsRuleLog.addTracks(\""+nodeIds+"\");");
			}
			ruleItem.setRuleResultInfo(ruleResultInfo);
			if ("1".equals(ruleManage.getIsSingle())) {// 单输出的时候添加互斥编号
				ruleItem.setActivationGroup(ruleManage.getCode());
			}
			ruleCollection.getListItem().add(ruleItem);
			priority--;
		}
		if(isfuntionMode) {
			/**
			 * drl修改为函数模式，全部的判断内容放在函数中
			 */
			return DroolsUtils.convert2DrlFunc(ruleCollection,null,RuleCollection.RULETREE,isSingle);
		}else {
			return DroolsUtils.convert2Drl(ruleCollection);
		}
	}
	
	public String generateDrl(DecisionSubNode node, List<String> ruleNameExtList, Map<String, DecisionSubNode> tempMap,boolean isfuntionMode)
			throws Exception {
		if(node==null)
			return "";
		String retStr = "";
		if (node.getNodeItems() != null && node.getNodeItems().size() > 0) {
			ruleNameExtList.add(node.getId());
			for (DecisionSubNodeItem item : node.getNodeItems()) {
				String leftOpt = item.getLeftOpt();
				if (!org.apache.commons.lang3.StringUtils.isEmpty(leftOpt)) {
					leftOpt = leftOpt.toUpperCase();
					leftOpt = leftOpt.replace("AND", "&&").replace("OR", "||");
				}
				String rightOpt = item.getRightOpt();
				if (!org.apache.commons.lang3.StringUtils.isEmpty(rightOpt)) {
					rightOpt = rightOpt.toUpperCase();
					rightOpt = rightOpt.replace("AND", "&&").replace("OR", "||");
				}
				leftOpt = leftOpt == null ? "" : leftOpt;
				rightOpt = rightOpt == null ? "" : rightOpt;
				retStr += leftOpt + genernalWhenStr(item.getClassName(),item.getNameEN(),item.getIsfuncparam()); 
//				if("1".equals(item.getIsfuncparam())) {
//					retStr += leftOpt + dataMap.get(item.getClassName()+item.getNameEN());
//				}else {
//					retStr = leftOpt + "ruleHelper.getValue($insertMap,\"" + item.getClassName() + "." + item.getNameEN() + "\")";
////					retStr += leftOpt + " this[\"" + item.getClassName() + "\"][\"" + item.getNameEN() + "\"]";
//				}
				if (!org.apache.commons.lang3.StringUtils.isEmpty(item.getPosition())) {
					retStr += ".get(" + item.getPosition() + ")";
				}
				if (item.getDataType().equals("String")) {
					if("null".equals(item.getControlValue().trim())) {
						String tmp = "";
						if("1".equals(item.getSymbol()) || "==".equals(item.getSymbol())) {
							tmp = retStr + "==null || "+retStr+"==\"\" \n";
						}else {
							tmp = retStr + "!=null && "+retStr+"!=\"\" \n";
						}
						retStr = tmp;
					}else if (org.apache.commons.lang3.StringUtils.isEmpty(item.getDomain())) {
						String result = item.getControlValue().trim();
						if (result.startsWith("{") && result.endsWith("}")) {
							Map<String, String> controlMap = (new ObjectMapper()).readValue(result, Map.class);
//							result = " this[\"" + controlMap.get("className") + "\"][\"" + controlMap.get("nameEN") + "\"]";
							result = genernalWhenStr(controlMap.get("className"),controlMap.get("nameEN"),controlMap.get("isfuncparam"));
							retStr += item.getSymbol() + result ;
						}else {
							 if (item.getSymbol().equals("startsWith") || item.getSymbol().equals( "endsWith")) {
		                            retStr += "." + item.getSymbol() + "(\"" + result + "\")";
		                     } else {
							        retStr += item.getSymbol() + "\"" + result + "\"";
		                     }
						}
					} else {
						String result = "";
						String  symbol = item.getSymbol();
						String controlValue = item.getControlValue().trim();
						symbol = symbol.equals("0") ? " not in " : " in ";
						for (String str : controlValue.substring(1, controlValue.length() - 1)
								.split(",")) {
							result += str + ",";
						}
						result = "(" + result.substring(0, result.length() - 1) + ")";	
						retStr += symbol + result + "\n";
					}
				} else if (item.getDataType().equals("Boolean")) {
					retStr += "==" + (item.getSymbol().equals("1") ? "true" : "false");
				} else {
					String controlValue = item.getControlValue().trim();
					String temp=item.getControlValue();
					if (controlValue.startsWith("{") && controlValue.endsWith("}")) {
						Map<String, String> controlMap = (new ObjectMapper()).readValue(controlValue, Map.class);
//						temp = " this[\"" + controlMap.get("className") + "\"][\"" + controlMap.get("nameEN") + "\"]";
						temp = genernalWhenStr(controlMap.get("className"),controlMap.get("nameEN"),controlMap.get("isfuncparam"));
					}else if(!StringUtils.isEmpty(item.getFormula())){
						temp = "MathHelper.invokeMath($insertMap,metaMap,\""+item.getFormula()+"\")";
					}else if (item.getDataType().equals("Date")){
						temp ="\""+temp+"\"";
					}
					retStr += item.getSymbol() + temp + "\n";
				}
				retStr += " " + rightOpt;
			}
		}else if(StringUtils.isNotEmpty(node.getNodehtml())) {
			ruleNameExtList.add(node.getId());
			String nodehtml = node.getNodehtml();
			retStr +=ruleParseExpService.parseFact(nodehtml, false, this);
//			List<Fact> facts = ruleParseDrl.transform2Facts(nodehtml,isfuntionMode);
//			retStr += DroolsUtils.facts2Condition(facts) + "\n";
		}
		if (tempMap.containsKey(node.getPid())) {
			DecisionSubNode parentNode = tempMap.get(node.getPid());
			String ret = generateDrl(parentNode, ruleNameExtList, tempMap,isfuntionMode);
			if (ret.length() > 0) {
				if(isfuntionMode) {
					retStr = ret.replace(" \n", "").replace("&&", "&&\n\t\t") + " &&\n\t\t " + retStr;
				}else {
					retStr += "," + ret;
				}
				
			}
		}
		return retStr;
	}
	private RuleItem getCustomRule(String ruleName, int priority, String factStr, String actionStr) {
		RuleItem rule = new RuleItem();
		rule.setEnabled("on");
		rule.setRuleName(ruleName);
		rule.setSalience(priority);
		DWhen dWhen = new DWhen();
		Fact fact = new Fact();
		fact.setContent(factStr);
		dWhen.setFirstFact(fact);
		DThen dThen = new DThen();
		Action action = new Action();
		action.setContent(actionStr);
		dThen.getListAction().add(action);
		rule.setdWhen(dWhen);
		rule.setdThen(dThen);
		return rule;
	}

	 
	/**
	 * 发布版本
	 */
	@Override
	public void updateVersion(RuleManage ruleManage) throws BizException {
		RuleTreeNode nodeCon = new RuleTreeNode();
		if (ruleManage.getOldId() != null){
		   nodeCon.setManageId(ruleManage.getOldId());	
		}else {
		   nodeCon.setManageId(ruleManage.getId());
		}
		nodeCon.setVersion(ruleManage.getOldVersion());
		List<RuleTreeNode> ruleTreeList =this.findList(nodeCon);
		
		RuleTreeParam paramCon = new RuleTreeParam();
		if (ruleManage.getOldId() != null){
		   paramCon.setManageId(ruleManage.getOldId());//COPY	
		}else {
		   paramCon.setManageId(ruleManage.getId());
		}
		paramCon.setVersion(ruleManage.getOldVersion());
		List<RuleTreeParam> treeParamList = ruleTreeParamService.findList(paramCon);
		//收集函数变量
		Map<String,RuleDataparams> funcparamMap = new HashMap<String, RuleDataparams>();
		// 收集引用数据
		Map<String, RuleReferenceData> refMap = new HashMap();
		String key = "";
		for (RuleTreeParam param : treeParamList) {
            key = param.getClassName() + "|" + param.getNameen() + "|out";
            ruleReferenceDataService.collectCommonData(param, key, "out", ruleManage, refMap);
		}
		
		RuleTreeConditions conditions = new RuleTreeConditions();
		conditions.setVersion(ruleManage.getOldVersion());
		if (ruleManage.getOldId() != null){
		  conditions.setManageId(ruleManage.getOldId());	
		}else {
		  conditions.setManageId(ruleManage.getId());
		}

		RuleReleModel  releModel = new  RuleReleModel();
		
		releModel.setVersion(ruleManage.getOldVersion());
		if (ruleManage.getOldId() != null){
			releModel.setManageId(ruleManage.getOldId());	
		}else 
			releModel.setManageId(ruleManage.getId());
		
	    List<RuleReleModel> releList =	this.ruleReleModelService.findList(releModel);

		List<RuleTreeConditions> treeCondList = ruleTreeConditionsService.findList(conditions);
		for (RuleTreeConditions condition : treeCondList) {
            if (StringUtils.isEmpty(condition.getSymbol())) {
                continue;
            }
            key = condition.getClassName() + "|" + condition.getNameen() + "|in";
            ruleReferenceDataService.collectCommonData(condition, key, "in", ruleManage, refMap);
            if (condition.getControlValue().startsWith("{") && condition.getControlValue().endsWith("}")) {
				try {
					Map<String, String> controlMap = (new ObjectMapper()).readValue(condition.getControlValue(), Map.class);
					String CONTROLKEY = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
					ruleReferenceDataService.collectFromMap(controlMap, CONTROLKEY, "in", ruleManage, refMap);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			List<RuleTreeParam> paramList = getdsInfo(ruleManage.getProjectCode(),condition.getFormula());
			if(paramList!=null){
				for (RuleTreeParam param : paramList) {
					param.setProjectCode(ruleManage.getProjectCode());
					param.setManageId(ruleManage.getId());
					param.setVersion(ruleManage.getVersion());
					key = param.getClassName() + "|"+ param.getNameen() + "|in";
					ruleReferenceDataService.collectCommonData(param, key, "in", ruleManage, refMap);
				}
			}
		}
		
		//将条件修改为html形式，数据信息就不再存储在RuleTreeConditions中，需要从RuleTreeNode中取
		RuleTreeNode   treeNodeInfo  = new  RuleTreeNode();
		treeNodeInfo.setVersion(ruleManage.getOldVersion());
		if (ruleManage.getOldId() != null){
			treeNodeInfo.setManageId(ruleManage.getOldId());
		}else {
			treeNodeInfo.setManageId(ruleManage.getId());
		}
		List<RuleTreeNode>  nodeList = this.findList(treeNodeInfo);
		for(RuleTreeNode node:nodeList) {
			String nodehtml = node.getNodehtml();
			if(StringUtils.isNotEmpty(nodehtml)) {
				this.ruleParseExpService.transformFactReference(nodehtml, ruleManage, refMap, funcparamMap);
			}
			
		}
		
		
		RuleTreeScene sceneCon = new RuleTreeScene();
		sceneCon.setVersion(ruleManage.getOldVersion());
		if (ruleManage.getOldId() != null){
			sceneCon.setManageId(ruleManage.getOldId());
		}else 
		   sceneCon.setManageId(ruleManage.getId());
		List<RuleTreeScene> treeSenceList = ruleTreeSceneService.findList(sceneCon);
		for (RuleTreeScene scene : treeSenceList) {
			key = scene.getClassName() + "|"+ scene.getNameen() + "|out";
			ruleReferenceDataService.collectCommonData(scene, key, "out", ruleManage, refMap);
		}
		//保存函数变量
        List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
        this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
		ruleReferenceDataService.saveReferenceData(refMap);
		this.insertBatch(ruleTreeList,new String[]{"id","manageId","version"},new Object[]{null,ruleManage.getId(),ruleManage.getVersion()},true);
		ruleTreeParamService.insertBatch(treeParamList,new String[]{"id","manageId","version"},new Object[]{null,ruleManage.getId(),ruleManage.getVersion()},true);
		ruleTreeConditionsService.insertBatch(treeCondList,new String[]{"id","manageId","version"},new Object[]{null,ruleManage.getId(),ruleManage.getVersion()},true);
 	    ruleTreeSceneService.insertBatch(treeSenceList,new String[]{"id","manageId","version"},new Object[]{null,ruleManage.getId(),ruleManage.getVersion()},true);
	    ruleReleModelService.insertBatch(releList, new String[]{"id","manageId","version"},new Object[]{null,ruleManage.getId(),ruleManage.getVersion()},true);

	}
	/**
	 * 模型复制
	 * @throws BizException
	 */
	@Override
	public void copyRule(RuleManage oldRuleManage, RuleManage ruleManage) throws BizException {
		ruleManage.setOldVersion(oldRuleManage.getVersion());
		ruleManage.setOldId(oldRuleManage.getId());
		this.updateVersion(ruleManage);
	}
	
	private List<RuleTreeParam> getdsInfo(String projectCode,String mathStr){
		if(StringUtils.isEmpty(mathStr) || !mathStr.contains("#{"))
			return null;

		Map<String,RuleDataparams> dstMap = new HashMap<String,RuleDataparams>();
		List<DataSetTreeVo> resultList = dataBomService.findBomListByProjCode(projectCode);
		for (DataSetTreeVo dataSetTreeVo : resultList) {
			for (DataSetTreeVo child : dataSetTreeVo.getChildren()){
				RuleDataparams param = child.getParam();
				param.setClassName(dataSetTreeVo.getNameEN());
				dstMap.put(child.getParam().getId(), param);
			}
		}
		
		List<String> idList = new ArrayList<String>();
		String reg = "#\\{{1}([0-9a-zA-Z\\-]+)\\}";
		//if (mathStr.matches(reg)) {
			Pattern pattern = Pattern.compile(reg);
			Matcher matcher = pattern.matcher(mathStr);
			String group = new String();
			while (matcher.find()) {
				group = matcher.group(1);
				idList.add(group);
			}
		//}
		List<RuleTreeParam> paramList = new ArrayList<RuleTreeParam>();
		for (String string : idList) {
			if(dstMap.containsKey(string)){
				RuleDataparams dp = dstMap.get(string);
				RuleTreeParam param = new RuleTreeParam();
				param.setClassName(dp.getClassName());
				param.setNameen(dp.getName());
				param.setNamecn(dp.getChzn());
				param.setDataType(dp.getType());
				param.setProjectCode(projectCode);
				paramList.add(param);
			}
		}
		return paramList;
	} 
	
	@Override
	public List<RuleDataparams> findFunctionParam(Map<String, String> map) {
		return this.ruleDataparamsService.findFunctionParam(map);
	}
	
	@Override
	public void clearVersion(RuleManage ruleManage,List<String> versions) {
		if(versions!=null&&versions.size()>0) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("projectCode", ruleManage.getProjectCode());
			map.put("manageId", ruleManage.getId());
			map.put("versions", versions);
			this.dao.deleteByMutilVersion(map);
			this.ruleTreeConditionsService.deleteByMutilVersion(map);
			this.ruleTreeParamService.deleteByMutilVersion(map);
		}
	}
}
